package Filter;

import Utils.WebTool;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

public class CartFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("User") == null) {
            if (!WebTool.isAjaxRequest(httpServletRequest)) {
                servletRequest.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest, servletResponse);
            } else {
                HashMap<String, Object> hashMap = new HashMap();
                hashMap.put("url", "/views/member/login.jsp");
                Gson gson = new Gson();
                String json = gson.toJson(hashMap);
                servletResponse.getWriter().write(json);
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }



}

@Override
public void destroy() {

}
}
